package com.jt.www.admin.market.controller;

import com.jt.www.admin.market.service.TeamService;
import com.jt.www.domain.po.TeamEntity;
import com.jt.www.domain.po.TeamFounderEntity;
import com.jt.www.domain.qo.SaveTeamMembersQO;
import com.jt.www.domain.qo.TeamFounderExportQO;
import com.jt.www.domain.qo.TeamFounderInfoQO;
import com.jt.www.domain.vo.TeamDetailVO;
import com.jt.www.domain.vo.TeamFounderInfoVO;
import com.jt.www.domain.vo.TeamMembersVO;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.util.DateUtils;
import com.jt.www.util.JsonUtil;
import com.jt.www.util.excel.CsvExportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "营销人员组织管理相关接口", tags = {"TEAM-INFO-API"}, description = "营销人员组织管理相关接口")
@RestController
@RequestMapping(value = "/team")
public class TeamController {
    public static final Logger log = LoggerFactory.getLogger(TeamController.class);

    @Autowired
    private TeamService teamService;

    /**
     * 团队创始人配置（修改时为变更创始人）
     *
     * @param teamFounderEntity
     * @return
     */
    @ApiOperation(value = "团队创始人配置", notes = "团队创始人配置", httpMethod = "POST")
    @PostMapping(value = "/saveTeamFounder", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity saveTeamFounder(@RequestBody TeamFounderEntity teamFounderEntity) {

        String findCode = "saveTeamFounder_" + System.currentTimeMillis();

        log.info("{} 团队创始人配置 入参：marketFounderEntity->{}", findCode, JsonUtil.object2Json(teamFounderEntity));

        return teamService.saveTeamFounder(findCode, teamFounderEntity);
    }

    /**
     * 团队成员配置
     *
     * @param saveTeamMembersQO
     * @return
     */
    @ApiOperation(value = "团队成员配置", notes = "团队成员配置", httpMethod = "POST")
    @PostMapping(value = "/saveTeamMembers", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity saveTeamMembers(@RequestBody SaveTeamMembersQO saveTeamMembersQO) {

        String findCode = "saveTeamMembers_" + System.currentTimeMillis();

        log.info("{} 团队成员配置 入参：saveTeamMembersQO->{}", findCode, JsonUtil.object2Json(saveTeamMembersQO));

        return teamService.saveTeamMembers(findCode, saveTeamMembersQO);
    }

    /**
     * 根据创始人ID查询小队列表
     *
     * @param teamFounderId
     * @return
     */
    @ApiOperation(value = "根据创始人ID查询小队列表", notes = "根据创始人ID查询小队列表", httpMethod = "GET")
    @GetMapping(value = "/queryTeams", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericListResponse<TeamEntity>> queryTeams(@ApiParam(value = "创始人ID", required = true) @RequestParam("teamFounderId") String teamFounderId) {

        String findCode = "queryTeams_" + System.currentTimeMillis();

        log.info("{} 根据创始人ID查询小队列表 入参：teamFounderId->{}", findCode, teamFounderId);

        return teamService.queryTeams(findCode, teamFounderId);
    }

    /**
     * 根据创始人ID查询未分组成员列表
     *
     * @param teamFounderId
     * @return
     */
    @ApiOperation(value = "根据创始人ID查询未分组成员列表", notes = "根据创始人ID查询未分组成员列表", httpMethod = "GET")
    @GetMapping(value = "/queryNoTeamMembersByFounderId", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericListResponse<TeamMembersVO>> queryNoTeamMembersByFounderId(@ApiParam(value = "创始人ID", required = true) @RequestParam("teamFounderId") Long teamFounderId,
                                                                                            @ApiParam(value = "成员ID(需要排除的成员)") @RequestParam(value = "memberId", required = false) Long memberId) {

        String findCode = "queryNoTeamMembersByFounderId_" + System.currentTimeMillis();

        log.info("{} 根据创始人ID查询未分组成员列表 入参：teamFounderId->{},memberId->{}", findCode, teamFounderId, memberId);

        return teamService.queryNoTeamMembersByFounderId(findCode, teamFounderId, memberId);
    }

    /**
     * 成员进/出队
     *
     * @param memberId
     * @param teamId
     * @param levelCode
     * @return
     */
    @ApiOperation(value = "成员进/出队", notes = "成员进/出队", httpMethod = "GET")
    @GetMapping(value = "/updateTeamMember", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity updateTeamMember(@ApiParam(value = "成员ID", required = true) @RequestParam("memberId") Long memberId,
                                           @ApiParam(value = "团队职级 0-业务经理；1-业务员；", required = true) @RequestParam("levelCode") String levelCode,
                                           @ApiParam(value = "小队ID", required = false) @RequestParam("teamId") Long teamId,
                                           @ApiParam(value = "转移至X小队", required = false) @RequestParam("newTeamId") Long newTeamId,
                                           @ApiParam(value = "小队成员ID(多个,分隔)", required = false) @RequestParam("memberIds") String memberIds) {

        String findCode = "updateTeamMember_" + System.currentTimeMillis();

        log.info("{} 进/出 入参：memberId->{},teamId->{},levelCode->{},newTeamId->{},memberIds->{}",
                findCode, memberId, teamId, levelCode, newTeamId, memberIds);

        if (null == memberId || StringUtils.isBlank(levelCode)) {
            return GenericDataResponse.ng("参数不能为空");
        }
        return teamService.updateTeamMember(findCode, memberId, teamId, levelCode, newTeamId, memberIds);
    }

    /**
     * 成员移除
     *
     * @param memberId
     * @return
     */
    @ApiOperation(value = "成员移除", notes = "成员移除", httpMethod = "GET")
    @GetMapping(value = "/removeTeamMember", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity removeTeamMember(@ApiParam(value = "成员ID", required = true) @RequestParam("memberId") String memberId) {

        String findCode = "removeTeamMember_" + System.currentTimeMillis();

        log.info("{} 成员移除 入参：memberId->{}", findCode, memberId);

        return teamService.removeTeamMember(findCode, memberId);
    }

    /**
     * 成员重置
     *
     * @param teamFounderId
     * @return
     */
    @ApiOperation(value = "成员重置", notes = "成员重置", httpMethod = "GET")
    @GetMapping(value = "/resetTeamMembers", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity resetTeamMembers(@ApiParam(value = "创始人ID", required = true) @RequestParam("teamFounderId") String teamFounderId) {

        String findCode = "resetTeamMembers_" + System.currentTimeMillis();

        log.info("{} 成员重置 入参：teamFounderId->{}", findCode, teamFounderId);

        return teamService.resetTeamMembers(findCode, teamFounderId);
    }

    /**
     * 根据创始人ID查询团队详细信息
     *
     * @param teamFounderId
     * @return
     */
    @ApiOperation(value = "根据创始人ID查询团队详细信息", notes = "根据创始人ID查询团队详细信息", httpMethod = "GET")
    @GetMapping(value = "/queryDetailByTeamFounderId", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericDataResponse<TeamDetailVO>> queryDetailByTeamFounderId(@ApiParam(value = "创始人ID", required = true) @RequestParam("teamFounderId") Long teamFounderId) {

        String findCode = "queryDetailByTeamFounderId_" + System.currentTimeMillis();

        log.info("{} 根据创始人ID查询团队详细信息 入参：teamFounderId->{}", findCode, teamFounderId);

        return teamService.queryDetailByTeamFounderId(findCode, teamFounderId);
    }

    /**
     * 根据小队ID查询小队业务员信息列表
     *
     * @param teamId
     * @return
     */
    @ApiOperation(value = "根据小队ID查询小队业务员信息列表", notes = "根据小队ID查询小队业务员信息列表", httpMethod = "GET")
    @GetMapping(value = "/queryMembersByTeamId", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity queryMembersByTeamId(@ApiParam(value = "小队ID", required = true) @RequestParam("teamId") Long teamId) {

        String findCode = "queryMembersByTeamId_" + System.currentTimeMillis();

        log.info("{} 根据小队ID查询小队业务员信息列表 入参：teamId->{}", findCode, teamId);

        return teamService.queryMembersByTeamId(findCode, teamId);
    }

    /**
     * 解散创始人团队
     *
     * @param teamFounderId
     * @return
     */
    @ApiOperation(value = "解散创始人团队", notes = "解散创始人团队", httpMethod = "GET")
    @GetMapping(value = "/disbandTeamFounder", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity disbandTeamFounder(@ApiParam(value = "创始人ID", required = true) @RequestParam("teamFounderId") Long teamFounderId) {

        String findCode = "disbandTeamFounder_" + System.currentTimeMillis();

        log.info("{} 解散创始人团队 入参：teamFounderId->{}", findCode, teamFounderId);

        return teamService.disbandTeamFounder(findCode, teamFounderId);
    }

    /**
     * 分页查询创始人信息（组织管理）
     *
     * @param teamFounderInfoQO
     * @return
     */
    @ApiOperation(value = "分页查询创始人信息", notes = "分页查询创始人信息", httpMethod = "POST")
    @PostMapping(value = "/queryTeamFounders", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity queryTeamFounders(@RequestBody TeamFounderInfoQO teamFounderInfoQO) {

        String findCode = "queryTeamFounders_" + System.currentTimeMillis();

        log.info("{} 查询营销人员列表 入参：teamFounderInfoQO->{}", findCode, JsonUtil.object2Json(teamFounderInfoQO));

        return teamService.queryTeamFounders(findCode, teamFounderInfoQO);
    }

    /**
     * 导出创始人信息
     *
     * @param response
     * @param teamFounderExportQO
     */
    @ApiOperation(value = "导出创始人信息", notes = "导出创始人信息")
    @GetMapping(value = "/exportTeamFounders")
    public void exportTeamFounders(HttpServletResponse response, TeamFounderExportQO teamFounderExportQO) {
        try {

            String findCode = "exportTeamFounders_" + System.currentTimeMillis();

            log.info("{} 导出创始人信息 入参：teamFounderExportQO->{}", findCode, JsonUtil.object2Json(teamFounderExportQO));

            // 查询需要导出的数据
            List<TeamFounderInfoVO> list = teamService.exportTeamFounders(findCode, teamFounderExportQO);

            // 构造导出数据结构
            String titles = "序号,创始人工号,创始人姓名,创始人手机号码,专属渠道,创始人所属机构,创始人所属部门,业务经理人数,业务员人数,总人数,团队创建时间";  // 设置表头
            String keys = "serialNo,marketerNo,marketerName,marketerPhone,channelName,branchName,departName,managerNum,memberNum,totalNum,createTime";  // 设置每列字段

            // 构造导出数据
            List<Map<String, Object>> datas = new ArrayList<>();
            Map<String, Object> map = null;

            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    map = new HashMap<>();
                    map.put("serialNo", i + 1);
                    map.put("marketerNo", list.get(i).getMarketerNo() + "\t");
                    map.put("marketerName", StringUtils.isNotBlank(list.get(i).getMarketerName()) ? list.get(i).getMarketerName() : "");
                    map.put("marketerPhone", list.get(i).getMarketerPhone());
                    map.put("channelName", list.get(i).getChannelName());
                    map.put("branchName", list.get(i).getBranchName());
                    map.put("departName", StringUtils.isNotBlank(list.get(i).getDepartName()) ? list.get(i).getDepartName() : "");
                    map.put("managerNum", list.get(i).getManagerNum());
                    map.put("memberNum", list.get(i).getMemberNum());
                    map.put("totalNum", list.get(i).getTotalNum());
                    map.put("createTime", DateUtils.conver(list.get(i).getCreateTime(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));

                    datas.add(map);
                }
            }

            // 设置导出文件前缀
            String fName = "组织信息_";

            // 文件导出
            OutputStream os = response.getOutputStream();
            CsvExportUtil.responseSetProperties(fName, response);
            CsvExportUtil.doExport(datas, titles, keys, os);
            os.close();
        } catch (Exception e) {
            log.error("创始人信息 导出失败" + e.getMessage(), e);
        }
    }

}
